<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-11-15
 * Time: 下午12:29
 */
class JsonController extends Controller {
    private $_nowtime;

    public function init() {
        parent::init();
        $this->_logininfo = $this->_session->offsetGet('loginInfos');
        $this->_nowtime = date('Y-m-d H:i:s' ,strtotime('now'));
    }

    /**
     *发布报价
     */
    public function PublishPriceAction(){
        global $_PublishTypeCfg,$_PublishStatusCfg;
        if($this->_request->isPost()){
            $Post = $this->_request->getPost();
            $Post['content'] = !empty($Post['content']) ? htmlspecialchars(trim($Post['content']),ENT_QUOTES,"UTF-8") : "";
            $Post['business_name'] = !empty($Post['business_name']) ? htmlspecialchars(trim($Post['business_name']),ENT_QUOTES,"UTF-8") : "";
            $Post['contacts'] = !empty($Post['contacts']) ? htmlspecialchars(trim($Post['contacts']),ENT_QUOTES,"UTF-8") : "";
            $Post['mobile'] = !empty($Post['mobile']) ? htmlspecialchars(trim($Post['mobile']),ENT_QUOTES,"UTF-8") : "";
            $json = new JsonModel();
            $data = array(
                'create_time'=>$this->_nowtime,
                'demand'=>$Post['content'],
                'business_name'=>$Post['business_name'],
                'phone'=>$Post['mobile'],
                'realname'=>$Post['contacts'],
                'status'=>$_PublishStatusCfg['wait_audit'],
                'type'=>$_PublishTypeCfg['1'],
                'ip'=>Tools::getRemoteAddr(),
            );
           $res =  $json->addPublish($data);
            $arr  = array();
            if($res && $res>0){
                $arr = array(
                    'code'=>'8',
                    'msg'=>'发布报价成功',
                );
                echo json_encode($arr);die();
            }else{
                $arr = array(
                    'code'=>'1',
                    'msg'=>'发布报价失败',
                );
                echo json_encode($arr);die();
            }
        }
        die();
    }


    /**
     *发布求购
     */

    public function PublishInquireAction(){
        global $_PublishTypeCfg,$_PublishStatusCfg;
        if($this->_request->isPost()){
            $Post = $this->_request->getPost();
            $Post['content'] = !empty($Post['content']) ? htmlspecialchars(trim($Post['content']),ENT_QUOTES,"UTF-8") : "";
            $Post['business_name'] = !empty($Post['business_name']) ? htmlspecialchars(trim($Post['business_name']),ENT_QUOTES,"UTF-8") : "";
            $Post['contacts'] = !empty($Post['contacts']) ? htmlspecialchars(trim($Post['contacts']),ENT_QUOTES,"UTF-8") : "";
            $Post['mobile'] = !empty($Post['mobile']) ? htmlspecialchars(trim($Post['mobile']),ENT_QUOTES,"UTF-8") : "";
            $json = new JsonModel();
            $data = array(
                'create_time'=>$this->_nowtime,
                'demand'=>$Post['content'],
                'business_name'=>$Post['business_name'],
                'phone'=>$Post['mobile'],
                'realname'=>$Post['contacts'],
                'status'=>$_PublishStatusCfg['wait_audit'],
                'type'=>$_PublishTypeCfg['2'],
                'ip'=>Tools::getRemoteAddr(),
            );
            $res =  $json->addPublish($data);
            $arr  = array();
            if($res && $res>0){
                $arr = array(
                    'code'=>'8',
                    'msg'=>'发布求购成功',
                );
                echo json_encode($arr);die();
            }else{
                $arr = array(
                    'code'=>'1',
                    'msg'=>'发布求购失败',
                );
                echo json_encode($arr);die();
            }
        }
        die();
    }

    /**
     *
     */
    public function getbusinessjsonAction(){
        if($this->_request->isPost()){
            $Post = $this->_request->getPost();
            $Post['business_id'] = !empty($Post['business_id']) ? htmlspecialchars(trim($Post['business_id']),ENT_QUOTES,"UTF-8") : "";
            $json = new JsonModel();
            $business = $json->getBusinessById($Post['business_id']);
            if(!empty($business)){
                echo json_encode($business);
                die();
            }
            die();
        }
    }

    /**
     *检测公司信息
     */
    public function checkbusinessjsonAction(){
        if($this->_request->isPost()){
            $Post = $this->_request->getPost();
            $Post['business_id'] = !empty($Post['business_id']) ? htmlspecialchars(trim($Post['business_id']),ENT_QUOTES,"UTF-8") : "";
            $Post['business_name'] = !empty($Post['business_name']) ? htmlspecialchars(trim($Post['business_name']),ENT_QUOTES,"UTF-8") : "";
            $Post['business_phone'] = !empty($Post['business_phone']) ? htmlspecialchars(trim($Post['business_phone']),ENT_QUOTES,"UTF-8") : "";
            $Post['contacts'] = !empty($Post['contacts']) ? htmlspecialchars(trim($Post['contacts']),ENT_QUOTES,"UTF-8") : "";
            $Post['mobile'] = !empty($Post['mobile']) ? htmlspecialchars(trim($Post['mobile']),ENT_QUOTES,"UTF-8") : "";
            //这边主要是获取公司的id并存入session
            //获取用户信息
            $user = new UserModel();
            $userinfo = $user->getListById($this->_logininfo['id']);

            if(empty($this->_session['quotation_id'])){
                $arr = array(
                    'code'=>99
                );
                echo json_encode($arr);die();
            }

            if(empty($Post['business_id'])&empty($Post['business_name'])){
                $arr = array(
                    'code'=>1
                );
                echo json_encode($arr);die();
            }
            $business = new UsersinvoiceModel();
            //如果 $Post['business_id'] 为空，说明没有存在公司信息，
            if(empty($Post['business_id'])&&!empty($Post['business_name'])){
                //先去查询公司名称是否存在

                $res = $business->getlineByRow("business_name",$Post['business_name']);
                if(!empty($res)){
                    $arr = array(
                        'code'=>2
                    );
                    echo json_encode($arr);die();
                }
                //这边要去创建公司信息
                $data = array(
                    'user_id'=>$userinfo['id'],
                    'title'=>$Post['business_name'],
                    'business_name'=>$Post['business_name'],
                    'business_remarks'=>$Post['business_name'],
                    'business_phone'=>$Post['business_phone'] ,
                    'contacts'=>$Post['contacts'],
                    'mobile'=>$Post['mobile'],
                    'is_default'=>'Y',
                    'create_uid'=>-1,//-1，表示自动创建
                    'create_time'=>$this->_nowtime,
                    'update_uid'=>-1,
                    'update_time'=>$this->_nowtime,
                    'visit' => '1',
                    'remark'=>"这是在认购下单的时候创建的默认公司",
                );

                $business_id = $business->add($data);
                if(!empty($business_id)){
                    $buydata = array(
                        'user_id'=>$userinfo['id'],
                        'business_id'=>$business_id,
                        'business_name'=>$Post['business_name'],
                        'business_phone'=>$Post['business_phone'] ,
                        'contacts'=>$Post['contacts'],
                        'mobile'=>$Post['mobile'],
                        'qq'=>''
                    );
                    $this->_session->offsetSet('buy_data',$buydata);
                    $arr = array(
                        'code'=>8
                    );
                    echo json_encode($arr);die();
                }
            }else{
                $buydata = array(
                    'user_id'=>$userinfo['id'],
                    'business_id'=>$Post['business_id'],
                    'business_name'=>$business->getOneByIdAndName($Post['business_id'],"business_name"),
                    'business_phone'=>$Post['business_phone'] ,
                    'contacts'=>$Post['contacts'],
                    'mobile'=>$Post['mobile'],
                    'qq'=>$business->getOneByIdAndName($Post['business_id'],"qq"),
                );
                $this->_session->offsetSet('buy_data',$buydata);
                $arr = array(
                    'code'=>8
                );
                echo json_encode($arr);die();
            }

            die();
        }
    }

    /**
     *检测是否登录
     */
    public function checklogionAction(){
        if($this->_request->isPost()) {
            $Post = $this->_request->getPost();
            $Post['quotetaion_id'] = !empty($Post['quotetaion_id']) ? (int)htmlspecialchars(trim($Post['quotetaion_id']),ENT_QUOTES,"UTF-8") : "";
            //这边先存储session，
            $this->_session->offsetSet('quote_id',$Post['quotetaion_id']);

            //这边判断是否有登录
            if(!$this->_session->has('loginInfos')) {
                die('5');
            }
            $login_info = $this->_session->offsetGet('loginInfos');
            if(empty($login_info['id'])){
                die('5');
            }else{
                die('8');
            }
            die();
        }
        die();
    }

    /**
     *修改保存用户信息
     */
    public function changeuserinfoAction(){
        if($this->_request->isPost()) {
            $Post = $this->_request->getPost();
            $Post['realname'] = !empty($Post['realname']) ? htmlspecialchars(trim($Post['realname']),ENT_QUOTES,"UTF-8") : "";
            $Post['sex'] = !empty($Post['sex']) ? htmlspecialchars(trim($Post['sex']),ENT_QUOTES,"UTF-8") : "";
            $Post['qq'] = !empty($Post['qq']) ? htmlspecialchars(trim($Post['qq']),ENT_QUOTES,"UTF-8") : "";
            $Post['email'] = !empty($Post['email']) ? htmlspecialchars(trim($Post['email']),ENT_QUOTES,"UTF-8") : "";
            $Post['tel'] = !empty($Post['tel']) ? htmlspecialchars(trim($Post['tel']),ENT_QUOTES,"UTF-8") : "";
            $user = new UserModel();
            //这边过滤筛选
            if(empty($Post['realname'])){
                die("1");
            }

            if(empty($Post['sex'])){
                die("2");
            }

            if(empty($Post['qq'])){
                die("3");
            }

            $feild = array(
                'realname'=>$Post['realname'],
                'sex'=>$Post['sex'],
                'qq'=>$Post['qq'],
                'email'=>$Post['email'],
                'tel'=>$Post['tel'],
            );

            $res = $user->updateById($this->_logininfo['id'],$feild);

            if($res){
                die("8");
            }else{
                die("4");
            }
            die();
        }
    }

    /**
     *修改密码
     */
    public function changepasswordAction(){
        if($this->_request->isPost()) {
            $Post = $this->_request->getPost();
            $Post['old_password'] = !empty($Post['old_password']) ? htmlspecialchars(trim($Post['old_password']),ENT_QUOTES,"UTF-8") : "";
            $Post['new_password'] = !empty($Post['new_password']) ? htmlspecialchars(trim($Post['new_password']),ENT_QUOTES,"UTF-8") : "";
            $Post['confirm_password'] = !empty($Post['confirm_password']) ? htmlspecialchars(trim($Post['confirm_password']),ENT_QUOTES,"UTF-8") : "";
            //查询登录用户的基本信息
            $user = new UserModel();
            $userinfo = $user->getListById($this->_logininfo['id']);

            if(empty($Post['old_password'])){
                die("1");
            }

            if(md5($Post['old_password'])!=$userinfo['password']){
                die("2");
            }

            if(empty($Post['new_password'])){
                die("3");
            }

            if(empty($Post['confirm_password'])){
                die("4");
            }

            if($Post['confirm_password'] !=  $Post['new_password']){
                die("5");
            }


            $feild = array(
                'password'=>md5($Post['new_password'])
            );

            $res = $user->updateById($this->_logininfo['id'],$feild);

            if($res && $res>0){
                    die("8");
            }else{
                die("6");
            }
            die();
        }
    }

    //求购保存
    public function save_quoteAction(){
        global $_BidPurchaseCfg,$_BuyStateCfg,$_SmsSendSwitch,$_SmsSendContent;
        if($this->_request->isPost()){
            $__now_time = $_SERVER['REQUEST_TIME'];
            $times = date("Y-m-d H:i:s",$__now_time);
            $Post = $this->_request->getPost();
            $inquire_search = new InquireModel();
                //查询报价人的信息
                // 取得用户信息
                $user = $this->_session->offsetGet ( 'loginInfos' );
                $userid=$user['id'];
            $u=new UserModel();
            $user_info = $u->UserInfo($userid);
                $ret_data =array(
                    'code' => '',
                    'msg'  => '',
                );
//                var_dump($user_info);exit;
                if(empty($user_info['qq']) || empty($user_info['business_name']) || empty($user_info['moblie'])){
                    $ret_data['code'] = "7";
                    $ret_data['msg'] = "提示：您好!您的用户信息未完善， <a href='/user/index' target='_blank' class='blue'> 请完善</a> 后在提交";
                    echo json_encode($ret_data);
                    die();
                }
                $_POST['product_id'] = empty($_POST['product_id']) ? '' : (int) $_POST['product_id'];

                $_POST['buy_id'] = empty($_POST['buy_id']) ? '' :(int)  $_POST['buy_id'];

                $_POST['content'] = empty($_POST['content']) ? '' : htmlspecialchars($_POST['content'],ENT_QUOTES,"UTF-8");

                $_POST['price'] = empty($_POST['price']) ? '' : htmlspecialchars($_POST['price'],ENT_QUOTES,"UTF-8");
                $_POST['num'] = empty($_POST['num']) ? '' : htmlspecialchars($_POST['num'],ENT_QUOTES,"UTF-8");
                $_POST['delivery_area'] = empty($_POST['delivery_area']) ? '' : htmlspecialchars($_POST['delivery_area'],ENT_QUOTES,"UTF-8");
                $_POST['delivery_time'] = empty($_POST['delivery_time']) ? '' : htmlspecialchars($_POST['delivery_time'],ENT_QUOTES,"UTF-8");

                //这边去除重复报价的信息，再重复报报价之前，组织提交
                $quote = $u->searchquote($user_info,$_POST['buy_id']);
                if(!empty($quote)){
                    foreach($quote as $k=>$v){
                        if($v['num']==$_POST['num']&& $v['price']==$_POST['price']){
                            $ret_data['code'] = "-6";
                            $ret_data['msg'] = "提示：非常抱歉，你已报过相同的信息，你不能重复报价";
                            echo json_encode($ret_data);
                            die();
                        }
                    }
                }
            //
                //这边要设置不能报自己的求购信息，所以要给个报价自己的提示信息
                $inquire = $u->searchinquire($user_info,$_POST['buy_id']);

                if(!empty($inquire)){
                    $ret_data['code'] = "-7";
                    $ret_data['msg'] = "提示：非常抱歉，你不能操作自己求购的信息";
                    echo json_encode($ret_data);
                    die();
                }

                if(empty($_POST['buy_id'])){
                    $ret_data['code'] = "6";
                    $ret_data['msg'] = "提示：非常抱歉，这个求购存在问题，请联系客服确认";
                    echo json_encode($ret_data);
                    die();
                }
                if(empty($_POST['price'])){
                    $ret_data['code'] = "5";
                    $ret_data['msg'] = "提示：非常抱歉，请严格填写报价信息。1";
                    echo json_encode($ret_data);
                    die();
                }
                if(empty($_POST['num'])){
                    $ret_data['code'] = "5";
                    $ret_data['msg'] = "提示：非常抱歉，请严格填写报价信息。2";
                    echo json_encode($ret_data);
                    die();
                }

                if(empty($_POST['delivery_area'])){
                    $ret_data['code'] = "5";
                    $ret_data['msg'] = "提示：非常抱歉，请严格填写报价信息。3";
                    echo json_encode($ret_data);
                    die();
                }else{
                    $com = new CommonModel();
                    $area_info = $com->getArea("region_name like '%{$_POST['delivery_area']}%'");
                    if(!empty($area_info)){
                        $area_id = $area_info['region_id'];
                    }else{
                        $area_id = "0";
                    }
                }

                $inquireinfo = $inquire_search->getInquireList("iq.id = '{$_POST['buy_id']}'");

                $data = array(
                    'user_id'           => $user_info['id'],
                    'business_id'       => $user_info['invoice_id'], //这里给客户报的默认公司ID
                    'inquiry_id'        => $_POST['buy_id'],
                    'organization_id'   => 1,
                    'department_id'     => 1,
                    'create_time'       => $times,
                    'create_uid'        => 1,
                    'update_time'       => $times,
                    'update_uid'        => 1,
                    'type'              => 'require',
                    'product_id'        => empty($_POST['product_id']) ? $inquireinfo['product_id'] : $_POST['product_id'],
                    'service_id' => $inquireinfo['service_id'],
                    'currency_id' => $inquireinfo['currency_id'],
                    'area_id' => $inquireinfo['area_id'],
                    'delivery_area' => $inquireinfo['delivery_area'],
                    'delivery_time' => $inquireinfo['delivery_time'],
                    'delivery_method' => $inquireinfo['delivery_method'],
                    'num' => $_POST['num'],
                    'price' => $_POST['price'],
                    'remark' => $_POST['content'],
                    'status' => $_BidPurchaseCfg['order'],
                );

                //z这里一旦有人报价，求购的状态就变为正在洽谈
                $this->_db_handler->beginTransaction();
                try {
                    $res_id = $this->_db_handler->insert("iq_quotation",$data);

                    //更新状态
                    if(!empty($res_id)){
                        //先判断当前状态如何是待报价必须更新到交易中
                        $statusinfo = $this->_db_handler->fetchRow("SELECT * FROM  `iq_inquiry` WHERE  id ='{$_POST['buy_id']}'");
                        if($statusinfo['status'] ==$_BuyStateCfg['audit']){
                            $ret = $this->_db_handler->update("iq_inquiry",array('status'=>$_BuyStateCfg['Negotiate']),"id ='{$_POST['buy_id']}'");
                        }
                    }

                    if($res_id && $res_id>0){
                        $ret_data['code'] = "8";
                        $ret_data['msg'] = "提示：报价成功！请您耐心等待联系！";

                        echo json_encode($ret_data);
                    }
                    $this->_db_handler->commit();
                    die();

                }catch (Exception $e) {
                    $this->_db_handler->rollBack();
                    echoJs('alert("'."{$e->getMessage()}".'"); parent.location = "/user/bulkup";');
                    die();
                }
                die();

        }
    }

    //公司认证
    public function licensesAction(){
        if($this->_request->isPost()) {
            $Post = $this->_request->getPost();
            $Post['business_id'] = !empty($Post['business_id']) ? htmlspecialchars(trim($Post['business_id']),ENT_QUOTES,"UTF-8") : "";

            $business = new UsersinvoiceModel();

            $userinvoice =  $business->getUserBusinessyName("user_id= '{$this->_logininfo['id']}' and id='{$Post['business_id']}'");

            if(empty($userinvoice)){
                Tools::dieJs('alert("公司名称和当前用户不同，请正确操作");history.go(-1);');
            }

            if(!empty($userinvoice['certificate'])){
                $certificate =   json_decode($userinvoice['certificate'],true);
            }else{
                $certificate = array(
                    'b_certificate'=>'',
                    'tr_certificate'=>'',
                    'oc_certificate'=>'',
                );
            }

            echo json_encode($certificate);die();
        }
        die();
    }

    //获取诚实

    public function getcityAction(){
        if($this->_request->isPost()){
            $Post = $this->_request->getPost();
            $Post['province_id'] = !empty($Post['province_id']) ? htmlspecialchars(trim($Post['province_id']),ENT_QUOTES,"UTF-8") : "";
            if(empty($Post['province_id'])){
                return null;
            }

            $json = new JsonModel();
            $data = $json->getAreaList($Post['province_id']);
            echo json_encode($data);die();
        }
    }


    //获取产品的价格走势

    public function getPricetrendAction(){
        global $_suppliyStateCfg;
        if($this->_request->isPost()){
            $search = new SearchModel();
            $Post = $this->_request->getPost();
            $Post['product_id'] = !empty($Post['product_id']) ? htmlspecialchars(trim($Post['product_id']),ENT_QUOTES,"UTF-8") : "";
            $Post['currency_id'] = !empty($Post['currency_id']) ? htmlspecialchars(trim($Post['currency_id']),ENT_QUOTES,"UTF-8") : "";
            $data =$search->getPreprice("iq.product_id = {$Post['product_id']} and iq.status = '{$_suppliyStateCfg['up']}' and iq.currency_id = '{$Post['currency_id']}'",$limit='12',$type='trend');
            $sn = count($data)-1;
            if(!empty($data)){
                foreach($data as $key=>$val){
                    if($key<$sn){
                        $price[]=(float)$val['price'];
                        $create_time[]=substr($val['create_time'],0,10);
                    }else{
                        $price[]=(float)$val['price'];
                        $create_time[]=substr($val['create_time'],0,10);
                    }
                }
            }
            $arr = array(
                'price'=>$price,
                'create_time'=>$create_time,
            );

            echo json_encode($arr);die();
        }
    die();
    }


    //获取产品--分页列表

    public function getProductAction(){

        $_GET['q'] = !empty($_GET['q']) ? htmlspecialchars(strtolower(trim($_GET["q"])),ENT_QUOTES,"UTF-8"):'';

        if (preg_match("/\?|\*|#/",$_GET['q'])) return; //非法字符
        $q_list = explode(" ",$_GET['q']);//按空格分隔
        $total = count($q_list);

        //删除数组内的空元素
        if ( $total > 0 ){
            for ($i=0;$i<$total;$i++){
                if (empty($q_list[$i])){
                    unset($q_list[$i]);
                }
            }
        }
        array_unshift( $q_list, array_shift( $q_list ));
        $total = count($q_list);

        $str ="1=1";
        //只输入了一个关键字
        if ($total == 1){
            $items = array();

            //完全匹配查询
            $data = $this->_db_handler->fetchAll("SELECT p.id,`p`.`product_name`,`pb`.`brand_name`, pc.cate_name FROM `product` p
	 LEFT JOIN `product_brands` `pb` ON(`pb`.`id` = `p`.`brand_id`)
	 LEFT JOIN `product_cates` `pc` ON(`pc`.`id` = `p`.`cate_id`)
	 WHERE p.`product_code` = '{$_GET['q']}'order by p.`id`");
            $cnt = count($data);
            if ($cnt > 0){
                for ($i=0;$i<$cnt;$i++){
                    echo "{$data[$i]['id']}|{$data[$i]['product_name']}|{$data[$i]['brand_name']}|{$data[$i]['cate_name']}\n";
                }
            }
            //模糊查询
            $data = $this->_db_handler->fetchAll("SELECT p.id,`p`.`product_name`,`pb`.`brand_name`, pc.cate_name FROM `product` p
	 LEFT JOIN `product_brands` `pb` ON(`pb`.`id` = `p`.`brand_id`)
	 LEFT JOIN `product_cates` `pc` ON(`pc`.`id` = `p`.`cate_id`)
	 WHERE p.`product_code` like '%{$_GET['q']}%' and p.`product_code`  <> '%{$_GET['q']}%' order by p.`id`");

            $cnt = count($data);
            if ($cnt > 0){
                for ($i=0;$i<$cnt;$i++){
                    echo "{$data[$i]['id']}|{$data[$i]['product_name']}|{$data[$i]['brand_name']}|{$data[$i]['cate_name']}\n";
                }
            }
        }elseif ($total > 1){//多个关键字

            for ($i=0;$i<$total;$i++){
                $str .= " and `product_code` like '%{$q_list[$i]}%'";
            }
            $data = $this->_db_handler->fetchAll("SELECT p.id,`p`.`product_name`,`pb`.`brand_name`, pc.cate_name FROM `product` p
	 LEFT JOIN `product_brands` `pb` ON(`pb`.`id` = `p`.`brand_id`)
	 LEFT JOIN `product_cates` `pc` ON(`pc`.`id` = `p`.`cate_id`)
	 WHERE 1 {$str} ");
            $cnt = count($data);
            if ($cnt > 0){
                for ($i=0;$i<$cnt;$i++){
                    echo "{$data[$i]['id']}|{$data[$i]['product_name']}|{$data[$i]['brand_name']}|{$data[$i]['cate_name']}\n";
                }
            }
        }else{

            $data = $this->_db_handler->fetchAll("SELECT p.d,`p`.`product_name`,`pb`.`brand_name`, pc.cate_name FROM `product` p
	 LEFT JOIN `product_brands` `pb` ON(`pb`.`id` = `p`.`brand_id`)
	 LEFT JOIN `product_cates` `pc` ON(`pc`.`id` = `p`.`cate_id`)
	 order by p.`id` limit 20");
            $cnt = count($data);
            if ($cnt > 0){
                for ($i=0;$i<$cnt;$i++){
                    echo "{$data[$i]['id']}|{$data[$i]['product_name']}|{$data[$i]['brand_name']}|{$data[$i]['cate_name']}\n";
                }
            }


        }
        die();
    }

}